package com.zelma.agent.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zelma.agent.dao.GroupbuyDao;
import com.zelma.agent.entity.GroupbuyEntity;
import com.zelma.agent.service.GroupbuyService;

@Service("groupbuyService")
@SuppressWarnings("all")
public class GroupbuyServiceImpl extends ServiceImpl<GroupbuyDao, GroupbuyEntity> implements GroupbuyService {

    @Autowired
    private GroupbuyDao groupbuyDao;

    @Autowired
    private RestHighLevelClient client;

    @Override
    public int groupSignNum(Integer groupbuyId) {
        return groupbuyDao.groupSignNum(groupbuyId);
    }

    @Override
    public List <GroupbuyEntity> findGroupBuyInfo (String groupbuyTitle,
                                                   Integer groupbuyWhetherStatus,
                                                   Integer groupbuyShowStatus,
                                                   String cname) throws IOException {

        //同步ES端口
        SearchRequest searchRequest = new SearchRequest("groupbuy");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //多条件查询
        BoolQueryBuilder builder = new BoolQueryBuilder();

        //每个条件分别查询
        if (groupbuyTitle!=null && !"".equals(groupbuyTitle)){
            builder.filter(QueryBuilders.matchQuery("groupbuyTitle",groupbuyTitle));
        }
        if (groupbuyWhetherStatus!=null){
            builder.filter(QueryBuilders.matchQuery("groupbuyWhetherStatus",groupbuyWhetherStatus));
        }
        if (groupbuyShowStatus!=null){
            builder.filter(QueryBuilders.matchQuery("groupbuyShowStatus",groupbuyShowStatus));
        }
        if (cname!=null && !"".equals(cname)){
            builder.filter(QueryBuilders.matchQuery("groupbuyAddress",cname));
        }

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightTitle =
                new HighlightBuilder.Field("groupbuyTitle");
        highlightTitle.highlighterType("unified");
        highlightBuilder.preTags("<span style='color:red'><b>");
        highlightBuilder.postTags("</b></span>");
        highlightBuilder.field(highlightTitle);
        searchSourceBuilder.highlighter(highlightBuilder);

        searchSourceBuilder.query(builder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
        long numHits = totalHits.value;
// whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
        TotalHits.Relation relation = totalHits.relation;
        float maxScore = hits.getMaxScore();
        ArrayList <GroupbuyEntity> list = new ArrayList <>();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            // do something with the SearchHit
            String index = hit.getIndex();
            String id = hit.getId();
            float score = hit.getScore();
            String sourceAsString = hit.getSourceAsString();
            GroupbuyEntity groupbuyEntity = JSON.parseObject(sourceAsString, new TypeReference <GroupbuyEntity>() {
            });
            groupbuyEntity.setGroupbuyId(Integer.valueOf(id));
            Map <String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlight = highlightFields.get("groupbuyTitle");
            if (highlight!=null){
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
                groupbuyEntity.setGroupbuyTitle(fragmentString);
            }
            list.add(groupbuyEntity);
        }

        return list;
    }

    @Override
    public void eslist () throws IOException {

        List <GroupbuyEntity> list = baseMapper.selectList(null);

        for (GroupbuyEntity groupbuyEntity : list) {
            IndexRequest request = new IndexRequest("groupbuy");
            request.id(String.valueOf(groupbuyEntity.getGroupbuyId()));
            String jsonString = JSONObject.toJSONString(groupbuyEntity);
            request.source(jsonString, XContentType.JSON);
            IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        }
        System.out.println("=======团购数据同步到ES结束=======");

    }

    @Override
    public Integer deleteByGroupBuyId (Integer groupbuyId) {

        GroupbuyEntity groupbuyEntity = baseMapper.selectById(groupbuyId);

        groupbuyEntity.setStatus(1);

        return baseMapper.updateById(groupbuyEntity);
    }
}